package com.simple.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.simple.annotation.Log;
import com.simple.entity.CodeResult;
import com.simple.entity.StatusCode;
import com.simple.utils.SysConfig;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登陆的方法
 * **/
@Controller
public class LoginController {

    private static final  Logger logger=LoggerFactory.getLogger(LoginController.class);

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @RequestMapping("/login.html")
    public String login(){
        return "login";
    }

    /**
     * 登录提交
     * @param username
     * @param password
     * */
    @Log("登录操作")
    @RequestMapping(value = "/loginSubmit.html")
    @ResponseBody
    public CodeResult login(String username, String password, Model model, HttpSession session,
                            HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try{
            subject.login(token);
        }catch (IncorrectCredentialsException e){
            return CodeResult.fail("密码错误");
        }catch (UnknownAccountException exception){
            return CodeResult.fail("用户不存在");
        }catch (DisabledAccountException e){
            return CodeResult.fail("账户未被激活");
        }catch(Exception e) {
        	logger.error("登录异常："+e);
        }
        request.getSession().setAttribute(SysConfig.USER_SESSION_KEY, username);
        session.setAttribute(SysConfig.USER_SESSION, SysConfig.getUser().getHeadPortrait());
        return CodeResult.success(StatusCode.LOGIN_SUCCESS);
    }

    //验证码
    @RequestMapping("/kaptcha.html")
    public void kaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //创建文字
        String capText = defaultKaptcha.createText();
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        // 将文字放入图片中
        BufferedImage bi = defaultKaptcha.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
    }

    /**
     * 验证验证码
     * @param kaptcha 参数验证码
     *
     */
    @RequestMapping("/checkKaptcha.html")
    @ResponseBody
    public CodeResult checkKaptcha(HttpServletRequest request) {
        String kaptcha = request.getParameter("kaptcha");
        // 获取session中的key
        String kaptchaExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        if (StringUtils.isNotBlank(kaptchaExpected)&&kaptcha.equals(kaptchaExpected)) {
            return CodeResult.success(StatusCode.SUCCESS);
        }
        return CodeResult.fail(StatusCode.FAIL);
    }

    //退出登录
    @Log("登出操作")
    @RequestMapping("/user/logout.html")
    public String  logout(Model model) {
        Subject subject=SecurityUtils.getSubject();
        subject.logout();
        return "login.html";
    }

}
